package com.estronger.shopmanage.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;
import android.view.View;

import com.estronger.shopmanage.ui.MainActivity;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.bean.B1Login;
import com.estronger.shopmanage.bean.B2Guide;
import com.estronger.shopmanage.bean.MenuPermission;
import com.estronger.shopmanage.utils.PrefUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.io.File;
import java.util.concurrent.TimeUnit;

import cn.jesse.nativelogger.NLogger;
import cn.jesse.nativelogger.formatter.SimpleFormatter;
import cn.jesse.nativelogger.logger.LoggerLevel;
import cn.jesse.nativelogger.util.CrashWatcher;
import okhttp3.OkHttpClient;

public class MyApplication extends MultiDexApplication {

	private static MyApplication application;
	private static int mainTid;
	private static Handler handler;
	public static B2Guide guide;
	public static B1Login login;

	public static ImageLoader imageLoader = ImageLoader.getInstance();
	public static DisplayImageOptions options;
	public static MainActivity mainActivity;
	public static String province;
	public static String address;
	public String SERVER_URL;
	public static double latitude = 0;
	public static double longitude = 0;
	public static String phone_id = android.os.Build.SERIAL;
	public static String jpush_id;
	public static String selectPeople;//选择的人(多人时用逗号分隔)
	public static String selectID;//选择的人(多人时用逗号分隔)
	//送货的要求刷新
	public static boolean isNeedToReflash = false;
	//安装的要求刷新
	public static boolean isNeedToReflash_inst = false;

	public static Boolean isLoginToServer = false;
	public static OkHttpClient client = null;

	public String getSERVER_URL() {
		SERVER_URL = PrefUtils.getString(MyApplication.getApplication().getApplicationContext(),"sERVER_URL",SERVER_URL == null?"":SERVER_URL);
		return SERVER_URL;
	}

	public void setSERVER_URL(String sERVER_URL) {
		PrefUtils.setString(MyApplication.getApplication().getApplicationContext(),"sERVER_URL",sERVER_URL);
		SERVER_URL = sERVER_URL;
	}

	public static String city = "";
	public static String cityID = "";
	public static int SCRENN_W;

	/*
	 * public static UserInfo user = new UserInfo(); public static ImageLoader
	 * imageLoader = ImageLoader.getInstance(); public static
	 * DisplayImageOptions options;
	 */

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this) ;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		SCRENN_W = getResources().getDisplayMetrics().widthPixels;
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		application = this;
		//本地保存
		Hawk.init(getApplicationContext()).build();
		client = new OkHttpClient.Builder()
				.writeTimeout(20, TimeUnit.SECONDS)
				.readTimeout(20, TimeUnit.SECONDS)
				.connectTimeout(20, TimeUnit.SECONDS)
				.build();
		mainTid = android.os.Process.myTid();
		handler = new Handler();
		initLoader();

		String loggerpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ShopManage/logs";
		File dir = new File(loggerpath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		/**日志管理**/
		NLogger.getInstance()
				.builder()
				.tag("家装门店")
				.loggerLevel(LoggerLevel.DEBUG)
				.fileLogger(true)
				.fileDirectory(loggerpath)
				.fileFormatter(new SimpleFormatter())
				.expiredPeriod(3)
				.catchException(true, new CrashWatcher.UncaughtExceptionListener() {
					@Override
					public void uncaughtException(Thread thread, Throwable ex) {
						NLogger.e("uncaughtException", ex);
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				})
				.build();
	}


	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

	public static MyApplication getApplication() {
		return application;
	}

	public static int getMainTid() {
		return mainTid;
	}

	public static Handler getHandler() {
		return handler;
	}

	public static String getUserCode() {
		if (login != null && login.data != null) {
			return login.data.usercode;
		} else {
			return "";
		}
	}

	private static void initLoader() {
		if (options == null) { // 设置图片在下载期间显示的图片
			options = new DisplayImageOptions.Builder()
					.showImageOnLoading(R.drawable.no_picture_icon_b)//goods_default
					.showImageForEmptyUri(R.drawable.no_picture_icon_b)// 设置图片Uri为空或是错误的时候显示的图片
					.showImageOnFail(R.drawable.no_picture_icon_b) // 设置图片加载/解码过程中错误时候显示的图片
					.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
					.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
					.imageScaleType(ImageScaleType.EXACTLY)// 设置图片以如何的编码方式显示
					.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
					// .considerExifParams(true) 是否考虑JPEG图像EXIF参数（旋转，翻转）
					// .displayer(new
					// FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
					// .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
					.build();
		}
	}

	public static void finishMain() {
		if (mainActivity != null) {
			mainActivity.finish();
			city = "";
			cityID = "";
		}
	}

	public void showDis(View v) {
		Log.i("MM", "w = " + getResources().getDisplayMetrics().widthPixels
				+ " h " + getResources().getDisplayMetrics().heightPixels);

	}
	//static 代码段可以防止内存泄露
	static {
		SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
			@Override
			public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
				layout.setPrimaryColorsId(R.color.bg_color, R.color.text);//全局设置主题颜色
				return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
			}
		});
		//设置全局的Footer构建器
		SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
			@Override
			public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
				//指定为经典Footer，默认是 BallPulseFooter
				//layout.setPrimaryColorsId(R.color.bg_color, android.R.color.black);//全局设置主题颜色
				return new ClassicsFooter(context).setDrawableSize(20);
			}
		});
	}
}
